package edu.whut.mall.admin.controller;

import edu.whut.mall.admin.model.Resources;
import edu.whut.mall.admin.model.RoleResources;
import edu.whut.mall.admin.service.IResourceService;
import edu.whut.mall.common.api.ResponseMap;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * Author: smq
 * Unit: D9lab
 * Date: 2021-06-15 11.22
 */
@Api(tags = {"角色管理器"}, description = "", produces = MediaType.APPLICATION_JSON_VALUE)
@RestController
@RequiredArgsConstructor
@RequestMapping("/role")
public class RoleController {

    private final IResourceService roleService;

    @ApiOperation(value = "查询角色对应的资源")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", value = "角色id", paramType = "form", dataType = "int", required = true)
    })
    @RequestMapping(value = "/getResourcesByRoleId", method = RequestMethod.POST)
    public Map<String,Object> getResourcesByRoleId(HttpServletRequest request, Integer roleId) throws Exception {
        ResponseMap map = ResponseMap.getInstance();
        List<Resources> result = roleService.getResourcesByRoleId(roleId);
        System.err.println(result);
        if (result.size() == 0) return map.putFailure("查无结果",0);
        else return map.putValue(result, "查询成功");
    }


    @ApiOperation("指定角色资源")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", value = "角色id", paramType = "form", dataType = "int", required = true),
            @ApiImplicitParam(name = "resourceIdString", value = "资源字符串", paramType = "form", dataType = "string", required = true)
    })
    @PostMapping("/assignResourceToRole")
    public Map<String,Object> assignResourceToRole(HttpServletRequest request,Integer roleId, String resourceIdString){
        ResponseMap map = ResponseMap.getInstance();
        List<RoleResources> result = roleService.assignResourceRole(roleId, resourceIdString);
        if (result == null) {
            return map.putFailure("角色资源分配失败",0);
        }
        return map.putValue(result,"分配成功");

    }
}
